#include "GTexture.h"
#include <math.h>

wchar_t* AnsiToUnicode(const char* szStr)
{
	int nLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0);
	if (nLen == 0)
	{
		return NULL;
	}
	wchar_t* pResult = new wchar_t[nLen];
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen);
	return pResult;
}


GTexture::GTexture()
{
	m_pBmp = NULL;
}

void GTexture::LoadNormalTex(const char* pName)
{
	wchar_t* pszName = AnsiToUnicode(pName);
	m_pBmp = new Gdiplus::Bitmap(pszName);
}

void GTexture::LoadTgaTex(const char* pName)
{
	m_pTgaTex = new TGAImage();
	m_pTgaTex->read_tga_file(pName);
}

void GTexture::FlipVertically()
{
	m_pTgaTex->flip_horizontally();
}

Vector3f GTexture::SampleTex(float fU, float fV)
{
	fU = fmod(fU, 1);
	fV = fmod(fV, 1);
	
	int uv0 = fU * m_pTgaTex->get_width();
	int uv1 = fV * m_pTgaTex->get_height();
	TGAColor c = m_pTgaTex->get(uv0, uv1);
	Vector3f res;
	for (int i = 0; i < 3; ++i)
		res[2 - i] = (float)((float)c[i] / 255.0f);
	return res;
}

Vector3f GTexture::SampleNormalTex(float fU, float fV)
{
	int nX = (int)(fU * GetWidth());
	int nY = (int)(fV * GetHeight());
	m_pBmp->GetPixel(nX, m_pBmp->GetHeight() - 1 - nY, &m_col);
	return Vector3f(m_col.GetRed(), m_col.GetGreen(), m_col.GetBlue());
}

int GTexture::GetWidth()
{
	return m_pTgaTex->get_width();
}

int GTexture::GetHeight()
{
	return m_pTgaTex->get_width();
}